<?php

class Settings extends CActiveRecord
{
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	public function tableName()
	{
		return '{{settings}}';
	}

	public function rules()
	{
		return array(
			array('key, value', 'required'),
			array('category', 'length', 'max'=>64),
			array('key', 'length', 'max'=>255),
			
			array('id, category, key, value', 'safe', 'on'=>'search'),
		);
	}

	public function relations()
	{
		return array(
		);
	}

	public function attributeLabels()
	{
		return array(
			'id' => tt('ID'),
			'category' => tt('Category'),
			'key' => tt('Key'),
			'value' => tt('Value'),
		);
	}

	public function search()
	{
		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('category',$this->category,true);
		$criteria->compare('key',$this->key,true);
		$criteria->compare('value',$this->value,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
			'pagination'=>array(
				'pageSize'=>param('adminPaginationPageSize', 20),
			),
		));
	}
	
	public function set($category, $key, $value)
	{
		if (param('cacheEnabled'))
		{
			Yii::app()->settings->set($category, $key, $value);
		}
		else
		{
			$command=Yii::app()->db->createCommand('SELECT id FROM '.$this->tableName().' WHERE `category`=:cat AND `key`=:key LIMIT 1');
			$command->bindParam(':cat', $category);
			$command->bindParam(':key', $key);
			$result=$command->queryRow();
			$value=@serialize($value);

			if(!empty($result))
				$command=Yii::app()->db->createCommand('UPDATE '.$this->tableName().' SET `value`=:value WHERE `category`=:cat AND `key`=:key');
			else
				$command=Yii::app()->db->createCommand('INSERT INTO '.$this->tableName().' (`category`,`key`,`value`) VALUES(:cat,:key,:value)');

			$command->bindParam(':cat', $category);
			$command->bindParam(':key', $key);
			$command->bindParam(':value', $value);
			$command->execute();
		}
	}
	
	public function get($category, $key='', $default=null)
	{
		if (param('cacheEnabled'))
		{
			return Yii::app()->settings->get($category, $key, $default);
		}
		else
		{
			$command=Yii::app()->db->createCommand('SELECT `key`, `value` FROM '.$this->tableName().' WHERE `category`=:cat');
			$command->bindParam(':cat', $category);
			$items=$command->queryAll();
			$result=array();
			
			foreach ($items as $item)
			{
				$result[$item['key']] = @unserialize($item['value']);
			}
			
			if (!empty($key))
				return (isset($result[$key]))?$result[$key]:$default;
			return $result;
		}
	}
	
	public function delete($category, $key)
	{
		return Yii::app()->settings->delete($category, $key);
	}
}